#include "trap.h"
#include "ysyxsoc.h"
#include "riscv.h"
#include "amtest.h"
#define IMGSIZE 208
uint32_t  a[IMGSIZE/4];
void spi_test(void) {
    outb(SPI_TX0,  0b11001110);
    outl(SPI_DIV,  0x0002); // 50M/2*(1+DIV_4999) = 5KHz =  0x1388
    outl(SPI_SS ,  0b10000000);    // bitrev
    outl(SPI_CTRL, 0x02d10);  // 16bit ,txne,rxpo
    uint32_t CtrlReg = inl(SPI_CTRL); 
    while((CtrlReg&0x00000100) == 0x00000100){
        CtrlReg = inl(SPI_CTRL); 
    }
    uint8_t rdata = inl(SPI_RX0)>>8;
    check(rdata == 0b01110011 );
}
uint32_t flash_read(uint32_t addr){
    outl(SPI_TX1,  0x03000000 + (addr & 0x00ffffff));
    outl(SPI_DIV,  0x0002); // 50M/2*(1+DIV_4999) = 5KHz =  0x1388
    outl(SPI_SS ,  0b00000001);    // ss flash
    outl(SPI_CTRL, 0x02540);  // 64bit ,TXne,RXpo, ass,MSB
    uint32_t CtrlReg = inl(SPI_CTRL); 
    while((CtrlReg&0x00000100) == 0x00000100){
        CtrlReg = inl(SPI_CTRL); 
    }
    uint32_t datatemp = inl(SPI_RX0);  
    return ((datatemp & 0xff000000) >> 24) | \
            ((datatemp & 0x00ff0000) >>  8) | \
            ((datatemp & 0x0000ff00) <<  8) | \
            ((datatemp & 0x000000ff) << 24) ; 
}

void flash2sram (void){

    for (size_t i = 0; i < IMGSIZE-4; i=i+4)
    {
        a[i/4] = flash_read(i);
    }
}

int main() {
    spi_test();
//    check(inl(FLASH_ADDR) == 0x00000413 );
//    outl(FLASH_ADDR,  0x03000000);
//    flash2sram ();
//    ((void(*)())(FLASH_ADDR)) ();

//    uint32_t str = flash_read(0);
//    check(str == 0x13121110 ); 
    return 0;
}








